<!-- 周期消费 -->
<template>
  <div>
    <Row>
      <Col>
        <Input
          style="width:200px"
          placeholder="请输入渠道名称"
          v-model="params.source_channel_name"
          @on-enter="changesearch"
          @on-clear="changesearch"
          clearable
          class="ivu-ml-16"
        ></Input>
        <!-- <Select  style="width:200px" v-model="params.source_channel_name" placeholder="请输入渠道名称">
            <Option v-for="item in channelList" :value="item.value" :key="item.value">{{ item.label }}</Option>
          </Select> -->
        <Select
          style="width:100px"
          placeholder="请选择"
          v-model="params.consume_status"
          @on-change="changesearch"
          clearable
          class="ivu-ml-16"
        >
          <Option
            v-for="item in typelList"
            :value="item.value"
            :key="item.value"
            >{{ item.label }}</Option
          >
        </Select>
      </Col>
      <Col class="ivu-ml-16">
        <Button
          type="warning"
          @click="changeAdd('add', { id: '' })"
          v-hasC="{
            name: '-v1-marketing-consume-update-consume-cycle',
            flag: '/v1/marketing/consume/update-consume-cycle',
          }"
          >周期消费录入</Button
        >
      </Col>
    </Row>
    <div class="ivu-mt-16">
      <Table
        :columns="columns"
        :data="data"
        :loading="tableloading"
        :max-height="550"
      >
        <template slot-scope="{ row }" slot="option">
          <a
            type="primary"
            @click="changeAdd('edit', row)"
            v-hasC="{
              name: '-v1-marketing-consume-update-consume-cycle2',
              flag: '/v1/marketing/consume/update-consume-cycle',
            }"
            :disabled="(row.consume_status == 3 || row.is_disabled) && false"
            v-if="row.consume_status !== -1"
            >编辑</a
          >
          <Divider
            type="vertical"
            v-if="row.consume_status !== -1"
            v-hasCC="[
              {
                name: '-v1-marketing-consume-update-consume-cycle2',
                flag: '/v1/marketing/consume/update-consume-cycle',
              },
              {
                name: '-v1-marketing-consume-delete-consume-cycle',
                flag: '/v1/marketing/consume/delete-consume-cycle',
              },
            ]"
          ></Divider>
          <a
            type="primary"
            :disabled="row.is_disabled"
            @click="deleteTag(row)"
            v-hasC="{
              name: '-v1-marketing-consume-delete-consume-cycle',
              flag: '/v1/marketing/consume/delete-consume-cycle',
            }"
            v-if="row.consume_status !== -1"
            >删除</a
          >
        </template>
      </Table>
      <div
        class="ivu-mt iuv-text-center"
        style="display:flex;justify-content: center;"
      >
        <Page
          show-total
          show-elevator
          show-sizer
          :total="total"
          :current.sync="params.page"
          :page-size="params.pageSize"
          :page-size-opts="pageOpts"
          @on-change="formSize"
          @on-page-size-change="formChangePage"
        ></Page>
      </div>
    </div>
    <Modal
      v-model="modalStatus"
      :title="modalTitle"
      width="1000"
      @on-cancel="handleCancel(formD)"
    >
      <Form ref="formD" :model="formData" inline>
        <div v-if="modalTitle == '录入'">
          <div v-for="(item, index) in formData.list" :key="index">
            <FormItem
              :prop="'list.' + index + '.source_channel_id'"
              :rules="{
                required: true,
                message: '请选择渠道',
                trigger: 'change',
              }"
            >
              <Select
                v-model="item.source_channel_id"
                placeholder="请输入渠道名称"
                v-width="160"
                :max-tag-count="3"
                clearable
              >
                <OptionGroup
                  :label="item.source_name"
                  v-for="item in channelList"
                  :key="item.id"
                >
                  <Option
                    v-for="its in item.children"
                    :value="its.id"
                    :key="its.id"
                    >{{ its.source_name }}</Option
                  >
                </OptionGroup>
              </Select>
            </FormItem>
            <FormItem
              :prop="'list.' + index + '.start_time'"
              :rules="{
                required: true,
                message: '请输入开始日期',
                trigger: 'change',
                type: 'date',
              }"
            >
              <DatePicker
                v-model="item.start_time"
                type="date"
                placeholder="请输入开始日期"
                style="width: 200px"
                @on-change="changeStart_time(item, index)"
              ></DatePicker>
            </FormItem>
            <FormItem
              :prop="'list.' + index + '.end_time'"
              :rules="{
                required: true,
                message: '请输入结束日期',
                trigger: 'change',
                type: 'date',
              }"
            >
              <DatePicker
                v-model="item.end_time"
                type="date"
                placeholder="请输入结束日期"
                style="width: 200px"
                @on-change="changeEnd_time(item, index)"
              ></DatePicker>
            </FormItem>
            <FormItem
              :prop="'list.' + index + '.cycle_consume'"
              :rules="{
                required: true,
                validator: validateconsume,
                trigger: 'blur',
                type: 'number',
              }"
            >
              <InputNumber
                v-model="item.cycle_consume"
                :min="1"
                :max="999999"
                placeholder="请输入合作金额..."
                style="width: 200px"
              ></InputNumber>
            </FormItem>
            <FormItem>
              <Button
                type="error"
                v-if="index !== 0"
                @click="handleRemove(index)"
                >删除</Button
              >
            </FormItem>
          </div>
          <div>
            <Row>
              <Col span="6">
                <Button
                  type="dashed"
                  @click="handleAdd"
                  :disabled="disabled"
                  icon="md-add"
                  >新增</Button
                >
              </Col>
            </Row>
          </div>
        </div>
        <div v-else>
          <FormItem
            prop="source_channel_id"
            :rules="{
              required: true,
              message: '请选择渠道',
              trigger: 'change',
            }"
          >
            <Select
              v-model="formData.source_channel_id"
              placeholder="请输入渠道名称"
              v-width="160"
              :max-tag-count="3"
              disabled
              clearable
            >
              <OptionGroup
                :label="item.source_name"
                v-for="item in channelList"
                :key="item.id"
              >
                <Option
                  v-for="its in item.children"
                  :value="its.id"
                  :key="its.id"
                  >{{ its.source_name }}</Option
                >
              </OptionGroup>
            </Select>
          </FormItem>
          <FormItem prop="start_Date">
            <DatePicker
              v-model="formData.start_Date"
              type="date"
              :disabled="+status === 2 || +status === 1 ? false : true"
              placeholder="请输入开始日期"
              style="width: 200px"
            ></DatePicker>
          </FormItem>
          <FormItem
            prop="end_Date"
            :rules="{
              required: true,
              validator: validateDate,
              trigger: 'change',
              type: 'date',
            }"
          >
            <DatePicker
              v-model="formData.end_Date"
              type="date"
              placeholder="请输入结束日期"
              style="width: 200px"
            ></DatePicker>
          </FormItem>
          <FormItem
            prop="cycle_consume"
            :rules="{
              required: true,
              validator: validateconsume,
              trigger: 'blur',
              type: 'number',
            }"
          >
            <InputNumber
              v-model="formData.cycle_consume"
              :min="1"
              :max="999999"
              placeholder="请输入合作金额..."
              style="width: 200px"
            ></InputNumber>
          </FormItem>
        </div>
      </Form>
      <div slot="footer">
        <Button @click="handleCancel('formD')">取消</Button>
        <Button
          type="primary"
          @click="handleSubmit('formD')"
          :disabled="disabled"
          :loading="btnLoading"
          >确定</Button
        >
      </div>
    </Modal>
  </div>
</template>
<script>
import dayjs from "dayjs";
import {
  consumecycleList,
  updateconsumeCycle,
  marketingconsumegetchannel,
  deleteonsumeCycle,
  checkconsumeCycle,
} from "@/api/hqapi/networkMarketing.js";
export default {
  data() {
    return {
      btnLoading: false,
      formD: "formD",
      columns: [
        {
          title: "渠道",
          minWidth: 150,
          fixed: "left",
          render: (h, params) => {
            return h(
              "span",
              `${params.row.parent_source_channel_name}/${params.row.source_channel_name}`
            );
          },
        },
        { title: "周期", key: "cycle_time", minWidth: 220 },
        { title: "合作金额", key: "cycle_consume", minWidth: 120 },
        {
          title: "状态",
          key: "",
          minWidth: 120,
          render: (h, params) => {
            return h(
              "span",
              params.row.consume_status == 1
                ? "未开始"
                : params.row.consume_status == 2
                ? "进行中"
                : params.row.consume_status == 3
                ? "已完成"
                : params.row.consume_status == -1
                ? "已删除"
                : ""
            );
          },
        },
        { title: "操作时间", key: "created_at", minWidth: 120 },
        { title: "操作人", key: "operation_name", minWidth: 120 },
        { title: "操作", slot: "option", width: "120", fixed: "right" },
      ],
      data: [],
      date: [],
      total: 0,
      params: {
        source_channel_name: "",
        consume_status: "",
        page: 1,
        pageSize: 10,
      },
      pageOpts: [10, 20, 50, 100],
      modalStatus: false,
      modalTitle: "",
      channelList: [],
      typelList: [
        {
          value: 1,
          label: "未开始",
        },
        {
          value: 2,
          label: "进行中",
        },
        {
          value: 3,
          label: "已结束",
        },
        {
          value: -1,
          label: "已删除",
        },
      ],
      index: 1,
      formData: {
        start_Date: "",
        end_Date: "",
        list: [
          {
            id: "",
            start_time: "",
            end_time: "",
            source_channel_id: "",
            cycle_consume: null,
          },
        ],
      },
      tableloading: false,
      disabled: false,
      status: "",
      options1: {
        disabledDate(date) {
          let temMonth = dayjs(new Date())
            .subtract(1, "month")
            .format("YYYY-MM");
          let temMonthStr = temMonth + "-01";
          let preMonth = dayjs(temMonthStr)
            .subtract(1, "day")
            .format("YYYY-MM-DD");
          let time = new Date(preMonth).getTime();
          return date && date.valueOf() < time;
        },
      },
      // newDate:new Date().setMonth(new Date().getMonth() - 1)
    };
  },
  mounted() {
    // console.log(this.$Date(this.newDate).format('YYYY-MM-DD'),'11')
    this.getdataList();
    this.getchannel();
  },
  methods: {
    validateconsume(rule, value, callback) {
      if (value === "") {
        callback(new Error("请填写合作金额"));
      } else {
        // console.log(value ,'qqq')
        if (!Number.isInteger(value)) {
          callback(new Error("请输入整数"));
        }
        callback();
      }
    },
    validateDate(rule, value, callback) {
      if (value === "") {
        callback(new Error("请选择结束时间"));
      } else {
        // console.log(this.$Date(this.formData.start_time).format('YY-MM-DD'),'1')
        if (
          this.$Date(this.formData.start_Date).format("YYYY-MM-DD") >
          this.$Date(this.formData.end_Date).format("YYYY-MM-DD")
        ) {
          callback(new Error("结束时间不能早于开始时间"));
        }
        callback();
      }
    },
    changesearch() {
      this.getdataList();
    },
    formSize(index) {
      this.params.page = index;
      this.getdataList();
    },
    formChangePage(e) {
      this.params.page = 1;
      this.params.pageSize = e;
      this.getdataList();
    },
    changeAdd(e, row) {
      this.modalStatus = true;
      if (e == "add") {
        this.modalTitle = "录入";
      } else {
        this.modalTitle = "编辑";
        this.formData = {
          id: row.id,
          start_Date: row.start_date,
          end_Date: row.end_date,
          source_channel_id: row.source_channel_id,
          cycle_consume: row.cycle_consume * 1,
        };
      }
      this.status = row.consume_status;
    },
    // 获取周期渠道
    getchannel() {
      marketingconsumegetchannel().then((res) => {
        this.channelList = res;
      });
    },
    // 获取列表数据
    getdataList() {
      this.tableloading = true;
      consumecycleList(this.params).then((res) => {
        this.data = res.list;
        this.total = res.total;
        this.tableloading = false;
      });
    },
    // 新增
    handleAdd() {
      this.index++;
      this.formData.list.push({
        id: "",
        start_time: "",
        end_time: "",
        source_channel_id: "",
        cycle_consume: null,
      });
    },
    // 删除
    handleRemove(index) {
      this.formData.list.splice(index, 1);
    },
    handleSubmit(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          this.btnLoading = true;
          if (this.modalTitle == "录入") {
            const data = this.formData.list.map((item) => {
              return { ...item };
            });
            data.forEach((el) => {
              if (el.start_time !== "" || el.end_time !== "") {
                el.start_time = this.$Date(el.start_time).format("YYYY-MM-DD");
                el.end_time = this.$Date(el.end_time).format("YYYY-MM-DD");
              } else {
                el.start_time = "";
                el.end_time = "";
              }
            });
            checkconsumeCycle({ list: data }).then((res) => {
              if (!res) {
                this.$Message["error"]({
                  content: "该时间段周期消费已存不能重复录入",
                });
                // this.$Modal.confirm({
                //   title: "提示",
                //   content: "<p>该时间段周期消费已存在是否继续录入?</p>",
                //   onOk: () => {
                //     updateconsumeCycle({ list: data }).then((res) => {
                //       this.$Message.success("新增成功!");
                //       this.handleCancel(name);
                //       this.getdataList();
                //     });
                //   },
                //   onCancel: () => {
                //     this.handleCancel(name);
                //   },
                // });
                this.btnLoading = false;
              } else {
                updateconsumeCycle({ list: data }).then((res) => {
                  this.$Message.success("新增成功!");
                  this.handleCancel(name);
                  this.getdataList();
                  this.btnLoading = false;
                });
              }
            });
          } else {
            console.log(
              this.$Date(this.formData.start_time).format("YYYY-MM-DD"),
              "11"
            );
            const params = {
              list: [
                {
                  id: this.formData.id,
                  start_time: this.formData.start_Date
                    ? this.$Date(this.formData.start_Date).format("YYYY-MM-DD")
                    : "",
                  end_time: this.formData.end_Date
                    ? this.$Date(this.formData.end_Date).format("YYYY-MM-DD")
                    : "",
                  source_channel_id: this.formData.source_channel_id,
                  cycle_consume: this.formData.cycle_consume,
                },
              ],
            };
            checkconsumeCycle(params).then((res) => {
              if (!res) {
                this.$Message["error"]({
                  content: "该时间段周期消费已存不能重复录入",
                });
                // this.$Modal.confirm({
                //   title: "提示",
                //   content: "<p>该时间段周期消费已存在是否继续录入?</p>",
                //   onOk: () => {
                //     updateconsumeCycle(params).then((res) => {
                //       this.$Message.success("编辑成功!");
                //       this.handleCancel(name);
                //       this.getdataList();
                //     });
                //   },
                //   onCancel: () => {
                //     this.handleCancel(name);
                //   },
                // });
                this.btnLoading = false;
              } else {
                updateconsumeCycle(params).then((res) => {
                  this.$Message.success("编辑成功!");
                  this.handleCancel(name);
                  this.getdataList();
                  this.btnLoading = false;
                });
              }
            });
          }
        }
      });
    },
    handleCancel(name) {
      this.$refs[name].resetFields();
      (this.formData = {
        start_Date: "",
        end_Date: "",
        list: [
          {
            id: "",
            start_time: "",
            end_time: "",
            source_channel_id: "",
            cycle_consume: null,
          },
        ],
      }),
        (this.disabled = false);
      this.modalStatus = false;
    },
    /* 删除 */
    deleteTag(row) {
      this.$Modal.confirm({
        title: "删除确认",
        content: "是否确认删除记录,删除后将无法恢复",
        loading: true,
        onOk: () => {
          deleteonsumeCycle({ id: row.id }).then((res) => {
            this.$Modal.remove();
            this.$Message.success("删除成功");
            this.getdataList();
          });
        },
      });
    },
    // 日期潘墩
    changeStart_time(item, idx) {
      // this.formData.list[idx].start_time = this.$Date(item.start_time).format('YYYY-MM-DD');
      // console.log(item.start_time,'item')
      // console.log(this.formData.list[idx].end_time,'date')
      if (
        this.formData.list[idx].end_time < item.start_time &&
        item.end_time !== ""
      ) {
        this.$Message.error("结束时间不能早于开始时间");
        this.disabled = true;
      } else {
        this.disabled = false;
      }
    },
    changeEnd_time(item, idx) {
      // this.formData.list[idx].end_time = this.$Date(item.end_time).format('YYYY-MM-DD');
      if (
        this.formData.list[idx].start_time > item.end_time &&
        item.start_time !== ""
      ) {
        this.$Message.error("结束时间不能早于开始时间");
        this.disabled = true;
      } else {
        this.disabled = false;
      }
    },
  },
};
</script>
